<template>
	<view class='article'>
		<view v-if="!showNoDataErr">
			<view class="author-info" v-if="(banner.avatar && banner.avatar != '') || (banner.author && banner.author != '') || (banner.bio && banner.bio != '')">
				<image @click="goUserDetail" v-if="(banner.avatar && banner.avatar != '')" class="avatar" :src="banner.avatar"></image>
				<text @click="goUserDetail" v-if="(banner.author && banner.author != '')" class="author-name">{{banner.author}}</text>
				<text v-if="(banner.bio && banner.bio != '')" class="author-mark">发表于：{{banner.bio}}</text>
			</view>
			
			<view class="articleContent">
				<div class="figure">
					<img style="max-width:100%;height:auto" :src="banner.screenshot">
				</div>
				<rich-text :nodes="banner.content"></rich-text>
			</view>
			<uni-fab
				:pattern="pattern"
				:content="content"
				:horizontal="horizontal"
				:vertical="vertical"
				:direction="direction"
				@trigger="trigger"
			></uni-fab>
		</view>
		<!-- <view class="title" v-if="(banner.title && banner.title != '')">
			<text>{{banner.title}}</text>
		</view> -->
		
		
		
		<view class="s-page" v-if="showNoDataErr">
			<view class="is-100vh is-flex is-column is-justify-center is-align-center ">
				<image src="../../static/error/no.png" style="width: 50%;margin-top: -110px" mode="widthFix"></image>
				<view class="has-title-color is-size-16 has-mgt-30">亲，没有数据</view>
				<view class="s-btn has-mgt-20">
					<view @click="goHome()" class="is-btn has-bg-red has-btn-radius ">返回首页</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const FAIL_CONTENT = '<p>获取信息失败</p>';
	
	import uniFab from '@/components/uni-fab/uni-fab.vue';
	import service from '../../common/service.js';
	
	let utils = require("@/common/util.js")
	let api = require("@/utils/api.js")
	
	export default {
		data() {
			return {
				banner: {},
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'vertical',
				showNoDataErr: false,
				collectionStatus: false,
				userinfo:{},
				token: null,
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor:"#007AFF"
				},
				imgUrls:[],
				content: [
					{
						iconPath: '/static/article/collection.png',
						selectedIconPath: '/static/article/collection_fill.png',
						text: '收藏',
						key:'collect',
						active: this.collectionStatus
					},
					{
						iconPath: '/static/article/picture.png',
						selectedIconPath: '/static/article/picture.png',
						text: '图片',
						key: 'picture',
						active: false
					},
					{
						iconPath: '/static/article/praise.png',
						selectedIconPath: '/static/article/praise_fill.png',
						text: '点赞',
						key:'like',
						active: false
					}
				]
			}
		},
		onShareAppMessage() {
			var data = JSON.parse(JSON.stringify(this.banner));
			data.content = "";
			data.transcodeContent = "";
			data.imageCache = "";
			data.avatar = "";
			data.screenshot = "";
			console.log(JSON.stringify(data))
			return {
				title: this.banner.title,
				path: '/pages/list/detail?query=' + JSON.stringify(data)
			}
		},
		onLoad(event) {
			if(!event.query){
				this.showNoDataErr = true;
				return;
			}
			// 目前在某些平台参数会被主动 decode，暂时这样处理。
			try {
				this.banner = JSON.parse(decodeURIComponent(event.query));
			} catch (error) {
				this.banner = JSON.parse(event.query);
			}
			this.init();
			this.getDetail();
			uni.setNavigationBarTitle({
				title: this.banner.title
			});
		},
		onNavigationBarButtonTap() {
			var that = this;
			if (this.providerList.length === 0) {
				uni.showModal({
					title: '当前环境无分享渠道!',
					showCancel: false
				});
				return;
			}
			let itemList = this.providerList.map(function(value) {
				return value.name;
			})
			uni.showActionSheet({
				itemList: itemList,
				success: (res) => {
					uni.share({
						provider: this.providerList[res.tapIndex].id,
						scene: this.providerList[res.tapIndex].type && this.providerList[res.tapIndex].type === 'WXSenceTimeline' ?
							'WXSenceTimeline' : "WXSceneSession",
						type: 2,
						title: '【涨知识】' + that.banner.author,
						summary: that.banner.title,
						imageUrl: that.banner.avatar,
						href: "https://m.bukaa.cn/#/pages/list/detail?query=" + encodeURIComponent(JSON.stringify({"id":that.banner.id})),
						success: (res) => {
							console.log("success:" + JSON.stringify(res));
						},
						fail: (e) => {
						}
					});
				}
			})
		},
		methods: {
			getDetail() {
				var that = this;
				uni.request({
					url: api.juejin_detail + this.banner.id,
					success: (res) => {
						if (res.statusCode == 200 && res.data.status == 'ok') {
							var detail = res.data.data.detail;
							if(!res.data.data || !res.data.data.detail){
								that.showNoDataErr = true;
								return;
							}
							var content = res.data.data.detail.content;
							content = content.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
							content = content.replace(/\<figure/gi, '<div class="figure" ');
							content = content.replace(/figure\>/gi, 'div>');
							content = content.replace(/\<pre/gi, '<blockquote class="pre" ');
							content = content.replace(/pre\>/gi, 'blockquote>');
							content = content.replace(/\n/gi, '<br>');
							content = content.replace(/\<p\>\<\/p\>/gi, '');
							//添加空格
							content = content.replace(/    /gi, '<div style="width:30px;height:10px;display: inline-block;"></div>');
							//移除多余的换行
							content = content.replace(/\<\/p\><br>/gi, '</p>');
							content = content.replace(/\<br><br>/gi, '<br>');
							content = content.replace(/\<\/div\><br>/gi, '</div>');
							content = content.replace(/\<\/h1\><br>/gi, '</h1>');
							content = content.replace(/\<\/h2\><br>/gi, '</h2>');
							content = content.replace(/\<\/h3\><br>/gi, '</h3>');
							content = content.replace(/\<\/ul\><br>/gi, '</ul>');
							content = content.replace(/\<\/ol\><br>/gi, '</ol>');
							content = content.replace(/\<\/blockquote\><br>/gi, '</blockquote>');
							
							//console.log(content);
							that.getImgUrls(content);
							var avatar;
							try{
								avatar = JSON.parse(res.data.data.user).avatarLarge || JSON.parse(res.data.data.user)['community']['wechat']['avatarLarge'];
							}catch(e){avatar = avatar || 'http://io.bukaa.cn/touxiang-girl.png'}
							that.banner = {
								id:res.data.data.id,
								title: res.data.data.title,
								content: content,
								author: JSON.parse(res.data.data.user).username,
								avatar: avatar,
								bio: utils.getDateDiff(utils.formatTime(new Date(res.data.data.updatedAt))),
								screenshot:res.data.data.screenshot,
								userId: res.data.data.userId,
							};
							that.getInfo();
						} else {
							that.showNoDataErr = true;
							return;
						}
					}
				});
			},
			getInfo(){
				var that = this;
				uni.request({
					url: 'https://bukaa.cn/api-cms/juejin/info/' + this.banner.id,
					header: {"Authorization":that.token},
					success: (res) => {
						if (res.statusCode == 200 && res.data.status == 'ok') {
								if(res.data.collection){
									that.content[0].active = true;
									that.collectionStatus = true;
								}
						}
					}
				})
			},
			addOrRemoveCollect(e){
				var that = this;
				if(!that.token){
					uni.showToast({
						title:'您还没登录哟',
						duration:500
					})
					that.content[0].active = false;
					return;
				}
				var url;
				if(that.collectionStatus){
					url = 'https://bukaa.cn/api-cms/article/collection/del/' + this.banner.id;
				}else{
					url = 'https://bukaa.cn/api-cms/article/collection/add/' + this.banner.id;
				}
				uni.request({
					url: url,
					header: {"Authorization":that.token},
					success: (res) => {
						if (res.statusCode == 200 && res.data.status == 'ok') {
								if(res.data){
									that.collectionStatus = !that.collectionStatus;
									e.that.openOrClose();
								}
						}
					},
					complete() {
						uni.hideLoading();
					}
				})
			},
			getImgUrls(str){
				var that = this;
				// 匹配图片（g表示匹配所有结果i表示区分大小写）
				let imgReg = /<img.*?(?:>|\/>)/gi
				// 匹配src属性
				let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
				let arr = str.match(imgReg)
				if(!arr)
					return;
				// console.log('所有已成功匹配图片的数组：' + arr)
				for (let i = 0; i < arr.length; i++) {
				  // console.log(arr[i])
				  let srcs = arr[i].match(srcReg)
				  // 获取图片地址
				  if (srcs && srcs[1]) {
					//console.log('已匹配的图片地址' + (i + 1) + '：' + srcs[1])					
					str = str.replace(arr[i], srcs[1])
					that.imgUrls.push(srcs[1]);
				  }
				}
			},
			init() {
				//用户信息
				this.token =  service.getToken();
				uni.getProvider({
					service: 'share',
					success: (e) => {
						console.log(JSON.stringify(e.provider));
						let data = []
						for (let i = 0; i < e.provider.length; i++) {
							switch (e.provider[i]) {
								case 'weixin':
									data.push({
										name: '分享到微信好友',
										id: 'weixin',
										sort:0
									})
									data.push({
										name: '分享到微信朋友圈',
										id: 'weixin',
										type:'WXSenceTimeline',
										sort:1
									})
									break;
								case 'sinaweibo':
									data.push({
										name: '分享到新浪微博',
										id: 'sinaweibo',
										sort:2
									})
									break;
								case 'qq':
									data.push({
										name: '分享到QQ',
										id: 'qq',
										sort:3
									})
									break;
								default:
									break;
							}
						} 
						this.providerList = data.sort((x,y) => {
							return x.sort - y.sort
						});
					},
					fail: (e) => {
						console.log('获取分享通道失败', e);
					}
				});
			},
			trigger(e) {
				this.content[e.index].active = !e.item.active;
				if(e.item.key === 'picture'){
					if(this.imgUrls.length > 0){
						uni.previewImage({
							urls: this.imgUrls
						});
					}else{
							uni.showToast({
								title:'无图片可预览',
							})
					}
					e.that.openOrClose();
				}else if(e.item.key === 'collect'){
					uni.showLoading({
						title:'loading...'
					})
					this.addOrRemoveCollect(e);
				}else{
					uni.showModal({
						title: '提示',
						content: `您${this.content[e.index].active?'选中了':'取消了'}${e.item.text}`,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
							e.that.openOrClose();
						}
					});
				}
			},
			goUserDetail(){
				var that = this;
				uni.navigateTo({
					url: '/pages/list/user?uid=' + this.banner.userId,
				});	
			},
			goHome(e){
				uni.switchTab({
					url: '/pages/list/list'
				});
			}
		},
		components: {
			uniFab
		}
	}
</script>

<style>
	page {
	  background: #fafafa;
	}
	
	.wxParse image{
		max-width: 100%;
	}

	.header-cover {
	  position: relative;
	  height: 500rpx;
	  overflow: hidden;
	}

	.header-cover image {
	  width: 100%;
	}

	.header-cover .mask {
	  position: absolute;
	  top: 0;
	  left: 0;
	  bottom: 0;
	  width: 100%;
	  background: rgba(0, 0, 0, 0.3);
	}

	.header-cover .desc {
	  position: absolute;
	  left: 0;
	  bottom: 0;
	  padding: 0 20rpx 60rpx 20rpx;
	  font-size: 40rpx;
	  color: #fff;
	  z-index: 10;
	}

	.header-cover .cover-source {
	  position: absolute;
	  right: 20rpx;
	  bottom: 20rpx;
	  font-size: 30rpx;
	  color: #fff;
	}

	.black-desc {
	  padding: 50rpx;
	  font-weight: bold;
	}

	/*article*/

	.article {
	  background: #fff;
	  padding: 15upx 15upx;
	}

	.article .title {
	  padding-bottom: 40rpx;
	  font-size: 40rpx;
	  font-weight: bold;
	}

	.article .author-info {
	  overflow: hidden;
	  height: 70rpx;
	  line-height: 70rpx;
	  font-size: 35rpx;
	  white-space: nowrap;
	  text-overflow: ellipsis;
	  margin-bottom: 16rpx;
	  margin-top: 0upx;
	  margin-left: 10upx;
	}

	.article .author-info .avatar {
	  float: left;
	  width: 70rpx;
	  height: 70rpx;
	  border-radius: 20rpx;
	}

	.article .author-info .author-mark {
	  color: #6a6a6a;
	  padding-top: 2upx;
	}

	.author-mark {
	  position: relative;
	  bottom: 0px;
	  padding: 0px;
	  margin: 0px;
	  font-size: 10px;
	  height: 60rpx;
	  overflow: hidden; /*自动隐藏文字*/
	  text-overflow: ellipsis; /*文字隐藏后添加省略号*/
	  white-space: nowrap; /*强制不换行*/
	  color: #69f;
	  width: 300rpx;
	}

	.article .author-info text {
	  display: block;
	  float: left;
	  padding-left: 10rpx;
	  margin-top: 10upx;
	}	
		
		
	a.listItemMetaTitle {
	  color: @heading-color;
	}
 

	article,aside,details,figcaption,figure,footer,header,main,menu,nav,section,summary {
	  display: block
	}

	audio,canvas,progress,video {
	  display: inline-block
	}

	audio:not([controls]) {
	  display: none;
	  height: 0
	}

	progress {
	  vertical-align: baseline
	}

	[hidden],template {
	  display: none
	}

	a {
	  background-color: transparent;
	  -webkit-text-decoration-skip: objects
	}

	a:active,a:hover {
	  outline-width: 0
	}

	abbr[title] {
	  border-bottom: none;
	  text-decoration: underline;
	  text-decoration: underline dotted
	}

	b,strong {
	  font-weight: inherit;
	  font-weight: bolder
	}

	dfn {
	  font-style: italic
	}

	h1 {
	  font-size: 2em;
	  margin: .67em 0
	}

	mark {
	  background-color: #ff0;
	  color: #000
	}

	small {
	  font-size: 80%
	}

	sub,sup {
	  font-size: 75%;
	  line-height: 0;
	  position: relative;
	  vertical-align: baseline
	}

	sub {
	  bottom: -.25em
	}

	sup {
	  top: -.5em
	}

	img {
	  border-style: none
	}

	svg:not(:root) {
	  overflow: hidden
	}

	code,kbd,pre,samp {
	  font-family: monospace,monospace;
	  font-size: 1em
	}

	figure {
	  margin: 1em 40px
	}

	hr {
	  box-sizing: content-box;
	  height: 0;
	  overflow: visible
	}

	button,input,select,textarea {
	  font: inherit;
	  margin: 0
	}

	optgroup {
	  font-weight: 700
	}

	button,input {
	  overflow: visible
	}

	button,select {
	  text-transform: none
	}

	[type=reset],[type=submit],button,html [type=button] {
	  -webkit-appearance: button
	}

	[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner {
	  border-style: none;
	  padding: 0
	}

	[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring {
	  outline: 1px dotted ButtonText
	}

	[type=checkbox],[type=radio] {
	  box-sizing: border-box;
	  padding: 0
	}

	[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button {
	  height: auto
	}

	[type=search] {
	  -webkit-appearance: textfield;
	  outline-offset: -2px
	}

	[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration {
	  -webkit-appearance: none
	}

	::-webkit-input-placeholder {
	  color: inherit;
	  opacity: .54
	}

	::-webkit-file-upload-button {
	  -webkit-appearance: button;
	  font: inherit
	}

	.iconfont {
	  font-family: iconfont!important;
	  font-style: normal;
	  -webkit-font-smoothing: antialiased;
	  -moz-osx-font-smoothing: grayscale
	}

	.icon-xlcollection:before {
	  content: "\E600"
	}

	.icon-xlchatbox:before {
	  content: "\E601"
	}

	

	#nprogress {
	  pointer-events: none
	}

	#nprogress .bar {
	  background: #007fff;
	  position: fixed;
	  z-index: 1031;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 2px
	}

	#nprogress .peg {
	  display: block;
	  position: absolute;
	  right: 0;
	  width: 100px;
	  height: 100%;
	  box-shadow: 0 0 10px #007fff,0 0 5px #007fff;
	  opacity: 1;
	  transform: rotate(3deg) translateY(-4px)
	}

	.nprogress-custom-parent {
	  overflow: hidden;
	  position: relative
	}

	.nprogress-custom-parent #nprogress .bar,.nprogress-custom-parent #nprogress .spinner {
	  position: absolute
	}


</style>
